import pytest
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from csvv import read_csv

# 读取测试数据
test_data = read_csv("testdata.csv")

# 定义 fixture，用于初始化和清理浏览器
@pytest.fixture(scope="function")
def browser():
    driver = webdriver.Chrome()
    driver.implicitly_wait(5)  # 隐式等待
    driver.maximize_window()
    yield driver
    driver.quit()

# 使用参数化测试
@pytest.mark.parametrize("test_case", test_data)
def test_commodity_unit(browser, test_case):
    # 打开登录页面
    browser.get("http://192.168.46.5:36336/login")  # 替换为实际登录页面 URL

    # 登录操作
    username_input = browser.find_element(By.NAME, "username")
    username_input.send_keys("XTGLY")
    time.sleep(2)

    password_input = browser.find_element(By.CLASS_NAME, "password")
    password_input.send_keys("123456")
    time.sleep(2)

    login_button = browser.find_element(By.ID, "signIn")
    login_button.click()
    time.sleep(2)

    # 进入商品单位页面
    commodity_unit_link = browser.find_element(By.LINK_TEXT, "商品单位")
    commodity_unit_link.click()
    time.sleep(2)

    # 点击新增按钮
    add_button = browser.find_elements(By.TAG_NAME, "button")[3]
    add_button.click()
    time.sleep(2)

    # 输入商品单位名称
    unit_name_input = browser.find_elements(By.CLASS_NAME, "el-input__inner")[4]
    unit_name_input.send_keys(test_case["商品单位名称"])
    time.sleep(2)

    # 点击保存按钮
    save_button = browser.find_element(By.XPATH, '"/html/body/div[2]/div/div[3]/div/button[1]"')
    save_button.click()
    time.sleep(2)

    # 获取提示信息
    message = browser.find_element(By.CLASS_NAME, "el-form-item__error").text
    time.sleep(2)

    # 断言
    assert message == test_case["预期结果"], f"实际结果：{el-form-item__error}，预期结果：{test_case['预期结果']}"

    # 如果断言失败，截图保存
    if message != test_case["预期结果"]:
        screenshot_path = f"screenshot_{int(time.time())}.png"
        browser.save_screenshot(screenshot_path)
        print(f"截图已保存至：{screenshot_path}")